package com.guochu;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@EnableTransactionManagement
@SpringBootApplication
/**
 * @PropertySources 为了让某个类调用 .properties 里写的常量
 *
 * <p>这里用了一个 数据库连接参数
 */
@EnableAsync
@PropertySources({
        @PropertySource(value = {"classpath:datasource.properties", "file:${spring.prop-path}/datasource.properties"},
                ignoreResourceNotFound = true,
                encoding = "UTF-8",
                name = "datasource.properties")
})
public class Application {
    protected static final Logger logger = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        logger.info("******************启动成功******************");
    }

    /**
     * 配置跨域访问
     *
     * <p>如果不这样设置，postman接口可正常访问，而前端程序会出现跨域问题
     *
     * @return
     */
    @Bean
    public org.springframework.web.filter.CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new org.springframework.web.filter.CorsFilter(source);
    }

    /**
     * 配置跨域访问
     *
     * @return
     */
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setMaxAge((long) (3600 * 24 * 30));
        return corsConfiguration;
    }
}
